const log4js = require('../../../utils/log4js');
const path = require('path');
const crypto = require('crypto');
const configure = require('little-man-config');
const storage_config = configure.get('storage');


const aliOssPolicyService = module.exports;

const $id = storage_config.oss.accessKeyId;
const $key = storage_config.oss.accessKeySecret;
const $host = storage_config.oss.host;
const $callback = storage_config.oss.uploadCallback;

aliOssPolicyService.getUploadPolicyWithCallback = async () => {
    let $end = new Date().getTime() + 1000 * 60 * 60 * 2; // policy 过期时间为2小时
    let $expiration = new Date($end).toISOString();

    let $policyString = {
        expiration: $expiration,
        conditions: [
            ['content-length-range', 0, 1000 * 1024 * 1024 * 1024], //最大文件大小.用户可以自己设置
        ]
    };

    let $callback_param = {
        'callbackUrl': $callback,
        'callbackBody': 'filename=${object}&size=${size}&userId=${userId}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
        'callbackBodyType': "application/x-www-form-urlencoded"
    };

    let $callback_string = JSON.stringify($callback_param);
    let $base64_callback_body = Buffer.from($callback_string).toString('base64');

    let $policy = JSON.stringify($policyString);
    let $base64_policy = new Buffer($policy).toString('base64');
    let $signature = crypto.createHmac('sha1', $key).update($base64_policy).digest('base64');

    return {
        OSSAccessKeyId: $id,
        host: $host,
        policy: $base64_policy,
        signature: $signature,
        success_action_status: '200',
        callback: $base64_callback_body,
        expire: $end,
    }
};

aliOssPolicyService.getFileKey = async (filename) => {
    let fid = helper.uuid();
    let fileType = helper.fileType(filename);
    return `user/${fileType.type}/${fid.substr(0, 2)}/${fid.substr(2, 2)}/${fid}${path.extname(filename)}`;
};